package com.songxh.shared.handler;

import com.songxh.core.base.CommonResult;
import com.songxh.core.shared.constant.RedisConsts;
import com.songxh.core.utils.RedisUtils;
import com.songxh.domain.service.api.ArticleService;
import com.songxh.domain.service.api.CommentService;
import com.songxh.domain.service.api.LikeService;
import com.songxh.infrastructure.db.pojo.Article;
import com.songxh.infrastructure.db.pojo.Comment;
import com.songxh.infrastructure.db.pojo.Like;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 点赞次数同步
 *
 * @author songxh
 * @create 2023-01-30-14:51
 */
@Component
@Slf4j
public class LikeNumberSycJobHandler {

    @Autowired
    private CommentService commentService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private LikeService likeService;


    @XxlJob("likeNumberSycJobHandler")
    public CommonResult LikeNumberSyc(String param) {
        Set<String> hashKey = RedisUtils.getHashKey(RedisConsts.S_LIKE_KEY);
        for (String key : hashKey) {
            //拆分
            Map<String, Object> keySplitMap = splitCell(key);
            //获取点赞数量  改：每个key就表示一个用户对一篇文章或者评论点赞，所以数量始终为1
            //Long likeNum = Long.valueOf(RedisUtils.getHash(RedisConsts.S_LIKE_KEY, key, Integer.class).toString());//java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
            //如果评论id有值，那么便是给评论点的赞
            if (StringUtils.isNotEmpty(keySplitMap.get("commentId").toString()) && !keySplitMap.get("commentId").toString().equals("null") && !keySplitMap.get("commentId").toString().equals("NULL")) {
                //修改评论表
                Comment comment = commentService.lambdaQuery()
                        .eq(Comment::getId, keySplitMap.get("commentId"))
                        .one();
                comment.setLikeCounts(comment.getLikeCounts() + 1);
                commentService.updateById(comment);

                //给点赞表存数据，以便后期使用
                Like like = new Like();
                like.setArticleId(Long.valueOf(keySplitMap.get("articleId").toString()));
                like.setUserId(Long.valueOf(keySplitMap.get("userId").toString()));
                like.setCommentId(Long.valueOf(keySplitMap.get("commentId").toString()));
                likeService.save(like);

                //删除缓存
                RedisUtils.deleteHash(RedisConsts.S_LIKE_KEY, key);
            } else if (StringUtils.isNotEmpty(keySplitMap.get("articleId").toString())) {
                Article article = articleService.lambdaQuery()
                        .eq(Article::getId, keySplitMap.get("articleId"))
                        .one();
                article.setLikeCounts(article.getLikeCounts() + 1);
                articleService.updateById(article);

                //给点赞表存数据，以便后期使用
                Like like = new Like();
                like.setArticleId(Long.valueOf(keySplitMap.get("articleId").toString()));
                like.setUserId(Long.valueOf(keySplitMap.get("userId").toString()));
                likeService.save(like);

                //删除缓存
                RedisUtils.deleteHash(RedisConsts.S_LIKE_KEY, key);
            }
        }
        return CommonResult.success();
    }


    /**
     * 拆分key，获取其中的值
     *
     * @param param
     * @return
     */
    private Map<String, Object> splitCell(String param) {
        String[] split = param.split("@");
        Map<String, Object> map = new HashMap<>();

        map.put("articleId", split[0]);
        map.put("userId", split[1]);
        map.put("commentId", split[2]);
        return map;
    }
}
